<?php
/**
 * 提现 记录
 */

namespace app\admin\controller;


use app\admin\model\UserModel;
use app\common\controller\Controller;
use think\Request;

use think\Db;
use think\Exception;
use app\admin\model\Withdraw as WithdrawModel;

class Withdraw extends Controller
{

    public function getIndex(Request $request)
    {
        $user_id= $request->param('user_id');

        $keyword=$request->param('keyword');
        $status= $request->param('status', '0');
        $order_type=$request->param('order_type',1);

        $search_type = $request->param('search_type');

        $account = '';
        if($search_type == 'user')
        {
            $user_id = UserModel::getUserIdByUserName($keyword);

        }else if($search_type == 'account')
        {
            $account=$keyword;
        }

        $query = WithdrawModel::getRecordQuery($user_id,$account,$status);


        if($order_type == 1)
        {
            $query->order('record_time desc');
        }else{
            $query->order('record_time');
        }
        $this->assign([
            'list'=>$query->paginate(),
            'keyword'=>$keyword,
            'order_type'=>$order_type,
            'search_type'=>$search_type,
            'status'=>$status
        ]);

        return $this->fetch('index');
    }
    public function postAjaxChangeStatus(Request $request)
    {
        $record_id = $request->post('id');
        $status = $request->post('status');
        if(!$record_id || ($status !=2  && $status !=3))
        {
            die(json_encode(['status'=>false,'msg'=>'参数错误']));
        }
        Db::startTrans();

        try{
            $info = WithdrawModel::getRecordStatusForUpdate($record_id);
            if(empty($info))
            {
                throw  new Exception("没有该记录");
            }
            if( $info['record_status']!=1)
            {
                throw  new Exception("该记录已处理，不能重复处理");
            }
            if($status ==2)
            {
                WithdrawModel::updateRecordCompleted($record_id);
            }
            if($status == 3)
            {
                WithdrawModel::refundRecord($record_id,$info);
            }
        }catch (Exception $e)
        {
            Db::rollback();
            die(json_encode(['status'=>false,'msg'=>$e->getMessage()]));

        }

        Db::commit();
        die(json_encode(['status'=>true,'msg'=>'']));
    }
}